/**
 * FileFind - ftp/shares indexing and search php engine
 * Module: agent-java
 * Description: Agent written in java language
 * Copyright (c) 2003-2010 Rage Steel, www.gt2.ru
 * ----------------------------------------------
 * $Id$
 */
package ru.ffind.agent.io;

import java.io.File;

import ru.ffind.agent.model.ListingStorage;

/**
 * 
 * File system scanner
 *
 * @author Rage Steel
 *
 */
public class FileScanner {
	
	/**
	 * 
	 * Starting point for the scanner
	 * 
	 */
	private final File root;
	
	/**
	 * 
	 * Create a new scanner
	 * 
	 * @param root Starting directory
	 * 
	 */
	public FileScanner(File root) {
		super();
		this.root = root;
	}
	
	private static String getFilePath(File file, String parentAbsPath) {
//		return "/".equals(file.getName()) ? file.getName() : (parentAbsPath + "/" + file.getName());
		return parentAbsPath.equals("/") ? (parentAbsPath + file.getName()) : (parentAbsPath + "/" + file.getName()); 
	}
	
	/**
	 * Scan filesystem and add listings to supplied storage
	 * 
	 * @param listingStorage storage for listings
	 */
	public void scan(ListingStorage listingStorage) {
		doScan(root, listingStorage, getFilePath(root, "/"));
	}
	
	private void doScan(File dirfile, ListingStorage listingStorage, String absPath) {
//		System.out.println("Scanning: " + absPath);
		// TODO add SecurityException handling
		File[] files = dirfile.listFiles();
		if (null == files) {
			listingStorage.put(absPath, ErrorDirectory.create(dirfile));
			return;
		}
		
		listingStorage.put(absPath, FileDirectory.create(dirfile, files));
		
		// Scan subdirectories
		for (File file: files) {
//			System.out.println("File: " + file);
			if (file.isDirectory()) {
				// FIXME Add checking for Link
				doScan(file, listingStorage, getFilePath(file, absPath));
			}
		}
	}
}
